import { VIEW_HISTORY, SEARCH_HISTORY } from './constant'

export const getViewHistory = () => {
    const item = window.localStorage.getItem(VIEW_HISTORY)
    return item ? JSON.parse(item) : []
}
export const setViewHistory = (history) => {
    let viewHistory = []
    const item = window.localStorage.getItem(VIEW_HISTORY)
    if (item) {
        viewHistory = JSON.parse(item)
    }
    const findIndex = viewHistory.findIndex((view) => view.aId === history.aId)
    if (findIndex !== -1) {
        viewHistory.splice(findIndex, 1)
    }
    viewHistory.push(history)
    window.localStorage.removeItem(VIEW_HISTORY)
    window.localStorage.setItem(VIEW_HISTORY, JSON.stringify(viewHistory))
}
/**
 * 获取搜索历史
 */

export const getSearchHistory = () => {
    const item = window.localStorage.getItem(SEARCH_HISTORY)
    return item ? JSON.parse(item) : []
}
/**
 * 添加搜索历史
 */
export const setSearchHistory = (history) => {
    let searchHistory = []
    const item = window.localStorage.getItem(SEARCH_HISTORY)
    if (item) {
        searchHistory = JSON.parse(item)
    }
    if (searchHistory.findIndex((view) => view.value === history.value) === -1) {
        searchHistory.push(history)
        clearSearchHistory()
        window.localStorage.setItem(SEARCH_HISTORY, JSON.stringify(searchHistory))
    }
}
/**
 * 清空搜索历史
 */
export const clearSearchHistory = () => {
    window.localStorage.removeItem(SEARCH_HISTORY)
}
